<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\api;


use Hyperf\HttpMessage\Stream\SwooleStream;
use xsl\basic\BaseController;

class File extends BaseController
{
    public function download($file, $dir, $filename)
    {
        $file = urldecode($file);
        $dir = urldecode($dir);
        $filename = urldecode($filename);
        // 检查文件是否存在
        $path = BASE_PATH . '/public/' . $file . '/' . $dir . '/' . $filename;
        if (!file_exists($path)) {
            return $this->error('File not found');
        }

        // 获取文件内容
        $fileContent = file_get_contents($path);

        var_dump(123);
        // 设置响应头
        $response = $this->response->withHeader('Content-Type', 'application/octet-stream')
            ->withHeader('Content-Disposition', 'attachment; filename="' . basename($path) . '"')
            ->withHeader('Content-Length', filesize($path));

        // 返回文件内容
        return $response->withBody(new SwooleStream($fileContent));
    }
}
